package utils

import "time"

type LoggerCacheWriter struct {
	logLvl        LogLevel
	logLvlOp      LogOp // 0:= 1:>=, 2:<=
	cacheQueue    *QueueTask
	cacheWriterCb func(cacheQueue *QueueTask)
}

func NewLoggerCacheWriter(maxcache int, intervalforCall time.Duration, cacheWriterCb func(cacheQueue *QueueTask)) *LoggerCacheWriter {
	rval := &LoggerCacheWriter{
		logLvl:        LogLV_0,
		logLvlOp:      LogOp_ALL,
		cacheWriterCb: cacheWriterCb,
	}
	rval.cacheQueue = NewQueueTaskFunc()
	rval.cacheQueue.ConfigMaxQueueSize(maxcache)
	rval.cacheQueue.ConfigIntervalCallBack(intervalforCall, rval.onCacheIntervalCb)
	rval.cacheQueue.Start()
	return rval
}

func (this *LoggerCacheWriter) onCacheIntervalCb() {
	if this.cacheWriterCb != nil {
		this.cacheWriterCb(this.cacheQueue)
	}

}

func (this *LoggerCacheWriter) LogWrite(rec *LogRecord) {
	if !IsFilter(this.logLvl, this.logLvlOp, rec) {
		return
	}
	this.cacheQueue.Push(rec)
}

func (this *LoggerCacheWriter) Close() {
	this.cacheQueue.Stop()
}

func (this *LoggerCacheWriter) SetLvlFilter(lvl LogLevel, matchOp LogOp) *LoggerCacheWriter {
	this.logLvl = lvl
	this.logLvlOp = matchOp
	return this
}
